from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework import serializers
from rest_framework.decorators import action
from rest_framework.response import Response

from goods.models import SPUSpecification, SPU


# 商品规格表序列化器



class SPUpceSerializer(serializers.ModelSerializer):

    # 关联嵌套序列化返回
    # 指定返回的spu名称
    spu = serializers.StringRelatedField(read_only=True)
    # 指定spu的id值 根据数据表中的字段作为序列化返回字段
    spu_id = serializers.IntegerField()
    class Meta:
        # 指定根据那个模型列生成序列化器
        model = SPUSpecification
        # 指定那些字段生成
        fields = ('id','name','spu','spu_id')


# SPU商品表序列化器
class SPUSerializer(serializers.ModelSerializer):
    """
        SPU商品表序列化器
    """
    # 关联嵌套序列化返回
    category1_id = serializers.IntegerField()
    category2_id = serializers.IntegerField()
    category3_id = serializers.IntegerField()
    brand_id = serializers.IntegerField()
    brand = serializers.StringRelatedField(read_only=True)

    class Meta:
        # 指定根据那个模型类生成序列化器字段
        model = SPU
        # 指定那些字段生成
        fields = '__all__'

    @action(methods=['post'], detail=False)
    def image(self, request):
        # 获取要保存的图片对象
        data = request.FILES.get('image')
        # 验证图片数据
        if data is None:
            return Response(status=500)
        # 建立fastFDS 的链接对象
        client = Fdfs_client(settings.FASTDFS_CONF)
        # 上传图片数据
        res = client.upload_by_buffer(data.read())
        # 判断上传状态
        if res['Status'] != 'Upload successed.':
            raise serializers.ValidationError('上传图片失败')
        # 获取上传的图片路径
        image_url = res['Remote file_id']

        # 结果返回
        return Response(
            {
                'img_url': settings.FDFS_URL + image_url
            },

            status=201
        )

    """
    "counts": "商品SPU总数量",
        "lists": [
            {
                "id": "商品SPU ID",
                "name": "SPU名称",
                "brand": "品牌名称",
                "brand_id": "品牌id",
                "category1_id": "一级分类id",
                "category2_id": "二级分类id",
                "category3_id": "三级分类id",
                "sales": "SPU商品销量",
                "comments": "SPU商品评论量",
                "desc_detail": "商品详情",
                "desc_pack": "商品包装",
                "desc_service": "售后服务"
            },
    """
